package com.kzw.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.kzw.entity.User;

/**
 * 权限过滤器：必须登陆后才能访问主页
 */
@WebFilter("/*")
public class SecurityFilter implements Filter {

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)resp;
		
		// 部分请求(css/js/jpg, login.jsp, /login)，应该放行
		// 除了login.jsp的JSP页面，以及/action/user/login这种/action/*请求，都要认证
		
		String uri = request.getRequestURI();
		if(StringUtils.containsAny(uri, ".jsp", "/action/")) {
			if(!StringUtils.containsAny(uri, "login.jsp", "/user/login")) {
				User user = (User)request.getSession().getAttribute("USER");
				if(user == null) {
					// 用户没有登陆, 跳转到登陆页面
					response.sendRedirect(request.getContextPath() + "/login.jsp");
				}
			}
		}
		// 其它情况
		chain.doFilter(req, resp);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

}
